/*
 * CSessionManager.cpp
 *
 *  Created on: 2011-9-7
 *      Author: stargui
 */

#include "CSessionManager.h"

//#define MAX_GROUPID 7
#define MAX_ONLINE_USER_NUM 6
#define HARDWARE_VIDEO_CHANNEL_NUM 6
#define  MAX_TASK_NODE		(MAX_ONLINE_USER_NUM * HARDWARE_VIDEO_CHANNEL_NUM + 30)

CSessionManager::CSessionManager()
{
	_messageClient 	= NULL;
	_sessionGroup.clear();
	_markedIndex		= 0x80000000;
	_usermax			= 0;
	m_devplaybackcount	= 0;
	_taskIndex				= 1;
	m_nodeindex			= -1;

	_sessionlist		= new taskSession_node[MAX_TASK_NODE];
	InitTaskList();
	printf("----------online--max--user:[%d]--------\n",MAX_ONLINE_USER_NUM);

}

CSessionManager::~CSessionManager()
{
	std::map<std::string, CSessionEntity*>::iterator it;
	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
	{
		if(it->second)
		{
			delete it->second;
		}
		it->second	= NULL;
	}
	_sessionGroup.clear();

	if(_sessionlist)
	{
		delete[] _sessionlist;
	}
	_sessionlist	= NULL;

}

void CSessionManager::ResetSession()
{
	_mutex.ThreadLock();
	std::vector<std::string> dead;
	std::map<std::string, CSessionEntity*>::iterator it;
	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
	{
		if(it->second && !it->second->passiveMode)
		{
			continue;
		}
		if(it->second)
		{
			delete it->second;
			it->second	= NULL;
		}
		dead.push_back(it->first);
	}

	std::vector<std::string>::iterator itr;
	for (itr = dead.begin(); itr != dead.end(); itr++)
	{
		_sessionGroup.erase(*itr);
	}
	_usermax		= 0;
	_mutex.ThreadUnlock();
}

// void CSessionManager::BindAdapterLayer(CAdapterLayer *adapter)
// {
// 	_adapter = adapter;
// 	_adapter->SetSessionCallback(boost::bind(&CSessionManager::AdapterCallback, this, _1, _2, _3,_4));
// }

// void CSessionManager::BindMessageClient(Common::CMessageClient * pMessageClient,CReportManage *pCReportManage)
// {
// 	_messageClient 	= pMessageClient;
// 	//_reportManage		= pCReportManage;
// 
// 	RegisterMediaMessage();
// }

/*CReportManage* CSessionManager::GetReportManage()
{
	//return _reportManage;
}
*/

bool CSessionManager::InsertSession(int handle, std::string session, bool passive,int level,std::string username,std::string password)
{
	_mutex.ThreadLock();

	//ֱ��ģʽ���û�������ת��ģʽ�¿ͻ������к�������֣�ֱ��ģʽ���û�����ȫ������λΪ1�����ת��ģʽ�����к���λΪ0
	//ת��ģʽ�µ����к����û��ͻ����Լ����ƣ���������Ŀ������Ϊ����ģ��ͨ�ţ�Ӧ��ش�ʱû�а취��ס����ͻ��˵����кţ�
	//����������������ֱ������ת�����������û������豸�ͻ��˶��ܶԻش���Ӧ��һһ��Ӧ��
	//ͬʱ��ת��ģʽ�£���Ϊ���豸���ӷ��������ʽ��豸��������û������û������б���ͳһ���?������ֵ��ֱ��ģʽ����
	//��ͬ����������Ϊֱ����ת��ģʽ��ҵ���?��ͬ�����ٴ�������ͬʱʹ�������passive��ǳ�����
	if(_markedIndex++ >= 0xFFFFFFFE )
	{
		_markedIndex	= 0x80000000;
	}

	if(passive)
	{
//		if(!CheckUserIsEnough(handle,session,level))
//		{
//			_mutex.ThreadUnlock();
//			return false;
//		}
		CSessionEntity *	sessionentity			= NULL;
		sessionentity								= new CSessionEntity();
		sessionentity->passiveMode				= passive;//net link mode
		sessionentity->sessionHandle 			= handle;//socket
		sessionentity->markedIndex 				= _markedIndex;//link id session socket
		sessionentity->sessionlevel 			= level;
		sessionentity->username					= username;
		sessionentity->password					= password;
		sessionentity->sessionstatus			= 0;
		sessionentity->loginstyle				= 0;

		datetime_t currenttime;
		memset(&currenttime,0,sizeof(datetime_t));
		CSystemTime::GetShareTime(&currenttime);

		memcpy(&sessionentity->logintime,&currenttime,sizeof(datetime_t));
		sessionentity->clientip.append(CPSocketUtils::GetIpbySocket(handle));

		_sessionGroup[session]					= sessionentity;
		_sessionGroup[session]->SetTaskCallback(boost::bind(&CSessionManager::TaskCallback,this,_1,_2,_3,_4,_5));
		_usermax++;	//add user

		Json::Value response;
		response[SESSION] 								= session;
		response[MODULE] 									= MODULE_CERTIFICATE;
		response[OPERATION] 								= CERTIFICATE_LOGIN;
		response[RESPONSE][CERTIFICATE_RETURN] 		= true;
		response[RESPONSE][ERRORCODE] 					= SUCCESS_OK;
		response[RESPONSE][ERRORCAUSE]					= EP_CN_SUCCESS_OK;

 		CProtocolFactory packet;
 		std::string sender 								= packet.Serialize(0, 0, response);
 		CPSocketUtils::Send(handle, sender.c_str(), sender.length(), 0,3000000,0);
// 
// 		sessionentity->OnInitRealstream();
// 		NoticeDevUserStatus();

#ifdef SUPPORTLOG
// 		LogItem_t		logitem;
// 		memset(&logitem,0,sizeof(LogItem_t));
// 		logitem.uLogType				= 9;
// 		logitem.stuStartTime.year	= sessionentity->logintime.year;
// 		logitem.stuStartTime.month	= sessionentity->logintime.month;
// 		logitem.stuStartTime.day		= sessionentity->logintime.day;
// 		logitem.stuStartTime.hour	= sessionentity->logintime.hour;
// 		logitem.stuStartTime.minute	= sessionentity->logintime.minute;
// 		logitem.stuStartTime.second = sessionentity->logintime.second;
// 		memcpy(logitem.LogContent.OperateLog.OperateUser,username.c_str(),username.length());
// 		std::string tempip			= sessionentity->clientip;
// 		int		i 						= 0;
// 		int	index						= tempip.find('.');
// 
// 		while(!tempip.empty() && index > 0)
// 		{
// 			logitem.LogContent.OperateLog.IpAddr[i++] = atoi(tempip.substr(0,index).c_str());
// 			tempip											= tempip.substr(index + 1,tempip.length() - index);
// 			index											= tempip.find('.');
// 		}
// 
// 		logitem.LogContent.OperateLog.IpAddr[i++]		= atoi(tempip.c_str());

// 		int		lenth										= sizeof(msgLogPackHeader_t) + sizeof(msgLogWriteItem_t);
// 		char logbuf[lenth];
// 		msgLogPackHeader_t	*loghead;
// 		loghead											= (msgLogPackHeader_t*)logbuf;
// 		loghead->u32Count									= 1;
// 
// 		msgLogWriteItem_t   *logdata;
// 		logdata											= (msgLogWriteItem_t*)loghead->body;
// 		logdata->key										= GetLogKey();
// 		memcpy(&logdata->item,&logitem,sizeof(LogItem_t));
// 
// 		_messageClient->SendMessage(0,MESSAGE_STORAGE_LOG_WRITE,0,logbuf,lenth,0);
#endif
		//DEBUG_WARNING("-add--user:[%s]--ip:[%s]--level:[%d]--[%d-%d,%d:%d]-[%d.%d.%d.%d]--\n",username.c_str(),sessionentity->clientip.c_str(),level,currenttime.month,currenttime.day,currenttime.hour,currenttime.minute,logitem.LogContent.OperateLog.IpAddr[0],logitem.LogContent.OperateLog.IpAddr[1],logitem.LogContent.OperateLog.IpAddr[2],logitem.LogContent.OperateLog.IpAddr[3]);
		DEBUG_WARNING("the new session add _markedIndex is [%02x],handle is [%d] session:[%s]",_markedIndex,handle,session.c_str());
	}
	_mutex.ThreadUnlock();

	return true;
}

int CSessionManager::InsertSessionTask(std::string session, std::string taskName, int taskHandle,unsigned int taskindex,void *_threadid)
{
	int status 						= -1;
	_mutex.ThreadLock();
	if (_sessionGroup.find(session) != _sessionGroup.end())
	{
		if(_sessionGroup[session])
		{
			status = _sessionGroup[session]->InsertSessionTask(taskindex,taskHandle, taskName,_threadid);
		}
		else
		{
			DEBUG_WARNING("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
		}
	}
	_mutex.ThreadUnlock();

	//DEBUG_WARNING("--status:[%d]--taskHandle:[%d]-session:[%s]-streamname:[%s]-taskindex:[%d]-\n",status,taskHandle,session.c_str(),taskName.c_str(),taskindex);
	return status;
}

void CSessionManager::RemoveSession(int handle, std::string session,bool passive )
{
	//DEBUG_WARNING("-----remove--session:[%s]--getpid:%d--\n",session.c_str(),getpid());
	_mutex.ThreadLock();
	if(passive)
	{
		if (_sessionGroup.find(session) != _sessionGroup.end())
		{
#ifdef SUPPORTLOG
		if(_sessionGroup[session])
		{
			datetime_t currenttime;
			memset(&currenttime,0,sizeof(datetime_t));
			CSystemTime::GetShareTime(&currenttime);

			LogItem_t		logitem;
			memset(&logitem,0,sizeof(LogItem_t));
			logitem.uLogType				= 31;
			logitem.stuStartTime.year	= currenttime.year;
			logitem.stuStartTime.month	= currenttime.month;
			logitem.stuStartTime.day		= currenttime.day;
			logitem.stuStartTime.hour	= currenttime.hour;
			logitem.stuStartTime.minute	= currenttime.minute;
			logitem.stuStartTime.second = currenttime.second;
			memcpy(logitem.LogContent.OperateLog.OperateUser,_sessionGroup[session]->username.c_str(),_sessionGroup[session]->username.length());
			std::string tempip			= _sessionGroup[session]->clientip;
			int		i 						= 0;
			int	index						= tempip.find('.');

			while(!tempip.empty() && index > 0)
			{
				logitem.LogContent.OperateLog.IpAddr[i++] = atoi(tempip.substr(0,index).c_str());
				tempip											= tempip.substr(index + 1,tempip.length() - index);
				index											= tempip.find('.');
			}

			logitem.LogContent.OperateLog.IpAddr[i++]		= atoi(tempip.c_str());

			int		lenth										= sizeof(msgLogPackHeader_t) + sizeof(msgLogWriteItem_t);
			char logbuf[lenth];
			msgLogPackHeader_t	*loghead;
			loghead											= (msgLogPackHeader_t*)logbuf;
			loghead->u32Count									= 1;

			msgLogWriteItem_t   *logdata;
			logdata											= (msgLogWriteItem_t*)loghead->body;
			logdata->key										= GetLogKey();
			memcpy(&logdata->item,&logitem,sizeof(LogItem_t));

			_messageClient->SendMessage(0,MESSAGE_STORAGE_LOG_WRITE,0,logbuf,lenth,0);
		}
#endif
			if(_sessionGroup[session])
			{
				delete  _sessionGroup[session];
			}
			_sessionGroup[session]		= NULL;
			_sessionGroup.erase(session);
			_usermax--;//sub user
			//DEBUG_WARNING("-----remove--session----end---_usermax:[%d]--\n",_usermax);
		}
		DEBUG_WARNING("-----remove--session----end--usercount:[%d]---\n",_sessionGroup.size());
	}
	else
	{
		if (_sessionGroup.find(session) != _sessionGroup.end())
		{
			if(_sessionGroup[session])
			{
				delete  _sessionGroup[session];
			}
			_sessionGroup[session]		= NULL;
			_sessionGroup.erase(session);
			DEBUG_WARNING("-----remove--session----end----\n");
		}
	}
	_mutex.ThreadUnlock();
}

void CSessionManager::RemoveSessionTask(std::string session,unsigned int taskindex)
{
	_mutex.ThreadLock();
	if (_sessionGroup.find(session) != _sessionGroup.end())
	{
		DEBUG_WARNING("---find----and-remove--task---[%s]--taskindex:[%d]-pid:[%d]--\n",session.c_str(),taskindex,getpid());
		if(_sessionGroup[session])
		{
			_sessionGroup[session]->RemoveSessionTask(taskindex);
		}
		else
		{
			DEBUG_WARNING("+++++++++++++++++++++++++++++++++++++++++++++++\n");
		}
	}
	_mutex.ThreadUnlock();
}

void CSessionManager::ActiveReleaseTask(std::string session)
{
	_mutex.ThreadLock();
	if (_sessionGroup.find(session) != _sessionGroup.end())
	{
		_sessionGroup[session]->ActiveReleaseTask();
	}
	_mutex.ThreadUnlock();

}

//chech status by level 0:session,1:task 2:all
void CSessionManager::QuerySessionTask(std::string session,int level, unsigned int taskindex,int &status)
{
	_mutex.ThreadLock();
	if (_sessionGroup.find(session) != _sessionGroup.end())
	{
		if(!_sessionGroup[session])
		{
			DEBUG_WARNING("+++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
			_mutex.ThreadUnlock();
			return ;
		}
		switch(level)
		{
			case 0:
				status = _sessionGroup[session]->sessionstatus;
				break;
			case 1:
				 _sessionGroup[session]->QuerySessionTask(taskindex,status);
				break;
			case 2:
				{
					status = _sessionGroup[session]->sessionstatus;
					_sessionGroup[session]->QuerySessionTask(taskindex,status);
				}
				break;
		}
	}
	_mutex.ThreadUnlock();
}

void CSessionManager::SessionGetDescribe(std::string &describe)
{

}

 int CSessionManager::SessionGetPermissions(std::string &user, std::string passwd, int &permissions,std::string mac,const int loginflag)
 {
 	return 0;
 }

bool CSessionManager::SearchSessionGroup(unsigned int marked, std::string &session)
{
	//marked��ÿ���û�������ֻ��session��Ӧ��������ת��ģʽ�º����е�仯����ת��ģʽ�¿ͻ��˻��ɶ���û���������
	//�豸Ӧ��֪��Ӧ�����һ���ͻ��ˣ��ʽ�marked��ת��ģʽ�¸ĳɿͻ��˵��������кţ�
	//�߼���һ�����кſ���Ψһ��ʾһ���ͻ�,������ת��ģʽ�¹涨ֻ�����(marked & 0x80000000)Ϊ0��Ϊ�ͻ����������к�
	std::map<std::string, CSessionEntity*>::iterator it;
	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
	{
		if (
			it->second &&
			(
			((it->second->markedIndex == marked) && (marked & 0x80000000)) ||
			(!(marked & 0x80000000) && !it->second->passiveMode)
			)
			)
		{
			session = it->first;
			return true;
		}
	}
	return false;
}
//ֱ�Ӵ�������Ӧ��
//messagetype 0:ֱ�Ӷ������Ӧ��,1:broadcast,2:֪ͨ���û�����״̬,3����Ҫ��ȡʵʱ�����û���Ϣ
bool CSessionManager::AdapterCallback(unsigned int source,std::string sessionid, Json::Value &response, int messagetype)
{
	//_mutex1.ThreadLock();
	//_mutex.ThreadLock();

	std::string session;
	switch(messagetype)
	{
		case 0:
			{
				if (SearchSessionGroup(source, session))
				{
					if(_sessionGroup[session]->sessionstatus	== 1)
					{
						//_mutex1.ThreadUnlock();
						//_mutex.ThreadUnlock();
						return true;
					}
					response[SESSION] 	= session;
					//CProtocolFactory packet;
					m_sender 	= m_packet.Serialize(0, 0, response);

					if(CPSocketUtils::Send(_sessionGroup[session]->sessionHandle, m_sender.c_str(), m_sender.length(), 0,3000000,0) < 0)
					{
						_sessionGroup[session]->sessionstatus			= 1;
					}
				}
			}
			break;
		case 1:
			{
				std::map<std::string, CSessionEntity*>::iterator it;
				for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
				{
					if(it->second && (it->second->sessionstatus == 1))
					{
						continue;
					}
					response[SESSION] 	= it->first;
					//CProtocolFactory packet;
					m_sender 	= m_packet.Serialize(0, 0, response);
					if(CPSocketUtils::Send(it->second->sessionHandle, m_sender.c_str(), m_sender.length(), 0,3000000,0) < 0)
					{
						it->second->sessionstatus			= 1;
					}

				}
			}
			break;
		case 2:
			{
				if (_sessionGroup.find(sessionid) != _sessionGroup.end())
				{
					if(_sessionGroup[sessionid])
					{
						response[SESSION] 	= sessionid;
						//CProtocolFactory packet;
						m_sender 	= m_packet.Serialize(0, 0, response);
						CPSocketUtils::Send(_sessionGroup[sessionid]->sessionHandle, m_sender.c_str(), m_sender.length(), 0,3000000,0);

						_sessionGroup[sessionid]->sessionstatus	= 1;
					}
				}
			}
			break;
		case 3:
			{
				std::string session								= "";
				if (SearchSessionGroup(source, session))
				{
					int i = 0;
					std::map<std::string, CSessionEntity*>::iterator it;
					for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
					{

						if(it->second && !it->second->sessionstatus && it->first != session)
						{
						//	DEBUG_WARNING("----------online--user:[%s]-----ip:[%s]--level:[%d]--------------\n",it->second->username.c_str(),it->second->clientip.c_str(),it->second->sessionlevel);
							response[RESPONSE][DEVICEMANAGE_USERINFO][i][DEVICEMANAGE_UN]	= it->second->username;
							response[RESPONSE][DEVICEMANAGE_USERINFO][i][DEVICEMANAGE_UID]	= session;
							response[RESPONSE][DEVICEMANAGE_USERINFO][i][DEVICEMANAGE_UL]	= it->second->sessionlevel;;
							response[RESPONSE][DEVICEMANAGE_USERINFO][i][DEVICEMANAGE_UIP]	= it->second->clientip;
							time_t		UtcTime;
							CSystemTime::DateTimeToUtcTime(&it->second->logintime,&UtcTime);
							response[RESPONSE][DEVICEMANAGE_USERINFO][i][DEVICEMANAGE_UT]	= (int)UtcTime;
							i++;
						}
					}
					response[RESPONSE][DEVICEMANAGE_CURRENTCOUNT]			=	_usermax;
					response[SESSION] 										= session;
					//CProtocolFactory packet;
					m_sender 										= m_packet.Serialize(0, 0, response);
					if(CPSocketUtils::Send(_sessionGroup[session]->sessionHandle, m_sender.c_str(), m_sender.length(), 0,3000000,0) < 0)
					{
						_sessionGroup[session]->sessionstatus				= 1;
					}
				}
			}
			break;
	}
	//_mutex1.ThreadUnlock();
	//_mutex.ThreadUnlock();
	return true;
}
//����ص�����������·����Ӧ��ָ���״ָ̬��
//type Ϊ0����������·����Ӧ��ָ���״ָ̬�Ϊ1������socket�쳣,
bool CSessionManager::TaskCallback(unsigned int source,unsigned int taskindex, Json::Value &response,int type,void* threadid)
{
	switch(type)
	{
		case 0:
			{
				//_mutex1.ThreadLock();
				//_mutex.ThreadLock();
				std::string session;
				if (SearchSessionGroup(source, session))
				{
					if(_sessionGroup[session]->sessionstatus				== 1)
					{
						//_mutex1.ThreadUnlock();
						//_mutex.ThreadUnlock();
						return true;
					}

					response[SESSION] 										= session;
					//CProtocolFactory packet;
					m_sender 										= m_packet.Serialize(0, 0, response);
					if(CPSocketUtils::Send(_sessionGroup[session]->sessionHandle, m_sender.c_str(), m_sender.length(), 0,3000000,0) < 0)
					{
						_sessionGroup[session]->sessionstatus				= 1;
					}
				}
				//_mutex1.ThreadUnlock();
				//_mutex.ThreadUnlock();
			}
			break;
	}

	return true;
}

bool CSessionManager::HandleSessionRequest(int handle, std::string session, Json::Value &request)
{
	bool status 		= false;
	try
	{
		_mutex.ThreadLock();
		//申请的指令是否时合法用户
		status = (_sessionGroup.find(session) != _sessionGroup.end());
		if(status)
		{
			if(_sessionGroup[session])
			{//处理媒体业务指令
				if (!_sessionGroup[session]->HandleSessionRequest(request))//ý��ָ���
				{
				//	_adapter->HandleSessionRequest(_sessionGroup[session]->markedIndex, request,_sessionGroup[session]->username,_sessionGroup[session]->password,_sessionGroup[session]->passiveMode);//������ָͨ���
				}
			}
			else
			{
				DEBUG_WARNING("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n");
			}
		}

		_mutex.ThreadUnlock();
	}
	catch(...)
	{
		_mutex.ThreadUnlock();
		status		= false;
	}

	return status;
}

bool CSessionManager::HandleSessionTask(int taskHandle, std::string session, CProtocolFactory *packet)
{

	return true;
}


bool CSessionManager::CheckUserIsEnough(int taskHandle,std::string session,int level)
{
	if(_usermax < MAX_ONLINE_USER_NUM)
		return true;

	if(3 == level)
		return false;

	std::map<std::string, CSessionEntity*>::iterator it;
	std::string	sessionid;
	int		first = 1;
	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
	{
		if(1 ==it->second->sessionstatus)
			continue;
		if(first)
		{
			if(2 == it->second->sessionlevel)//���ҵȼ�Ϊ2��
			{
				sessionid		= it->first;
				first			= 0;
				continue;
			}
		}
		if(it->second->sessionlevel == 3)//���ҵȼ�Ϊ3��
		{
			sessionid			= it->first;
			break;
		}
	}

	switch(level)
	{
	case 1:
		{
			if((_sessionGroup.end() == it) &&(1 == first))//û�еͼ��û���ȫ��ʱ��������Ա
			{
				return false;
			}
		}
		break;
	case 2:
		{
			if(_sessionGroup.end() == it)//û�еȼ�Ϊ3���û�
			{
				return false;
			}
		}
		break;
	}

	//֪ͨ�����û����û���ǿ��������
	Json::Value response;
	response[MODULE]						= MODULE_DEVICEMANAGE;
	response[OPERATION]					= DEVICEMANAGE_NOTICEUSERINFO;
	//response[PARAMETER][DEVICEMANAGE_USERNAME]	= request[PARAMETER][DEVICEMANAGE_USERNAME];
	response[PARAMETER][DEVICEMANAGE_USERSESSION] = session;
	response[PARAMETER][ERRORCODE]		= OFFLINEBYLOWRIGHT;
	response[PARAMETER][ERRORCAUSE]		= EP_CN_OFFLINEBYLOWRIGHT;

//	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
//	{
//		if(it->second->sessionstatus	==1)
//		{
//			continue;
//		}
		//DEBUG_WARNING("------------it->second->sessionHandle:[%d]----------session:(%s)---------\n",it->second->sessionHandle,it->first.c_str());
	//	response[SESSION] 				= it->first;
		response[SESSION] 				= sessionid;
		CProtocolFactory packet;
		std::string sender 				= packet.Serialize(0, 0, response);
		CPSocketUtils::Send(_sessionGroup[sessionid]->sessionHandle, sender.c_str(), sender.length(), 0,3000000,0);
	//}

	//��֪ͨ������
	_sessionGroup[sessionid]->sessionstatus		= 1;

	return true;
}

/*
int	CSessionManager::NoticeDevUserStatus()
{
	msgOnlineUsers_t onlineuserlist;
	memset(&onlineuserlist,0,sizeof(msgOnlineUsers_t));
	std::map<std::string, CSessionEntity*>::iterator it;
	int index								= 0;
	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
	{
		if(it->second && !it->second->sessionstatus && it->second->passiveMode)
		{
			memcpy(onlineuserlist.stuOLUser[index].szUUID,it->first.c_str(),it->first.length());
			memcpy(onlineuserlist.stuOLUser[index].szUserName,it->second->username.c_str(),it->second->username.length());
			memcpy(onlineuserlist.stuOLUser[index].szUserIP,it->second->clientip.c_str(),it->second->clientip.length());
			onlineuserlist.stuOLUser[index].stuLoginTime.year	= it->second->logintime.year;
			onlineuserlist.stuOLUser[index].stuLoginTime.month	= it->second->logintime.month;
			onlineuserlist.stuOLUser[index].stuLoginTime.day		= it->second->logintime.day;
			onlineuserlist.stuOLUser[index].stuLoginTime.hour	= it->second->logintime.hour;
			onlineuserlist.stuOLUser[index].stuLoginTime.minute	= it->second->logintime.minute;
			onlineuserlist.stuOLUser[index].stuLoginTime.second	= it->second->logintime.second;
			index++;
		}
	}
	onlineuserlist.iOnlineCount			= index;
	return _adapter->NoticeDevUserStatus(onlineuserlist);
}*/

// void CSessionManager::GetOnlineUser(	msgOnlineUsers_t &onlineuserlist)
// {
// 	std::map<std::string, CSessionEntity*>::iterator it;
// 	int index								= 0;
// 	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
// 	{
// 		if(it->second && !it->second->sessionstatus && it->second->passiveMode)
// 		{
// 			memcpy(onlineuserlist.stuOLUser[index].szUUID,it->first.c_str(),it->first.length());
// 			memcpy(onlineuserlist.stuOLUser[index].szUserName,it->second->username.c_str(),it->second->username.length());
// 			memcpy(onlineuserlist.stuOLUser[index].szUserIP,it->second->clientip.c_str(),it->second->clientip.length());
// 			onlineuserlist.stuOLUser[index].stuLoginTime.year	= it->second->logintime.year;
// 			onlineuserlist.stuOLUser[index].stuLoginTime.month	= it->second->logintime.month;
// 			onlineuserlist.stuOLUser[index].stuLoginTime.day		= it->second->logintime.day;
// 			onlineuserlist.stuOLUser[index].stuLoginTime.hour	= it->second->logintime.hour;
// 			onlineuserlist.stuOLUser[index].stuLoginTime.minute	= it->second->logintime.minute;
// 			onlineuserlist.stuOLUser[index].stuLoginTime.second	= it->second->logintime.second;
// 			index++;
// 		}
// 	}
// 	onlineuserlist.iOnlineCount			= index;
// }

void CSessionManager::SendAlarmInfo(std::string session)
{
	//_adapter->SendAlarmStateinfo(_sessionGroup[session]->markedIndex);
}

// int CSessionManager::CheckRightFun(std::string username,std::string password,FunRightType_m funtype,void *extra,unsigned int &result)
// {
// 	return _adapter->CheckFunRight(username,password,funtype,extra,result);
// }

void CSessionManager::InitTaskList()
{
	memset(_sessionlist,0,sizeof(taskSession_node) * MAX_TASK_NODE);
	memset(m_remoteplayback,0,sizeof(int) * MAX_GROUPID);
}

// void CSessionManager::ChanageUserPassAndName(msgUserList_t	userlist)
// {
// 	std::map<std::string, CSessionEntity*>::iterator it;
// 	int permissions								= 0;
// 
// 	_mutex.ThreadLock();
// 	for (it = _sessionGroup.begin(); it != _sessionGroup.end(); it++)
// 	{
// 		if(it->second && !it->second->sessionstatus && it->second->passiveMode)
// 		{
// 			if(_adapter->CheckUserIsOk(it->second->username, it->second->password,permissions,it->second->clientmac,it->second->loginstyle))
// 			{
// 				Json::Value response;
// 				response[MODULE]						= MODULE_DEVICEMANAGE;
// 				response[OPERATION]					= DEVICEMANAGE_NOTICEUSERINFO;
// 				response[PARAMETER][DEVICEMANAGE_USERSESSION] = it->first;
// 				response[PARAMETER][ERRORCODE]		= OFFLINEBYLOWRIGHT;
// 				response[PARAMETER][ERRORCAUSE]		= EP_CN_OFFLINEBYLOWRIGHT;
// 
// 				response[SESSION] 					= it->first;
// 				CProtocolFactory packet;
// 				std::string sender 					= packet.Serialize(0, 0, response);
// 				CPSocketUtils::Send(_sessionGroup[it->first]->sessionHandle, sender.c_str(), sender.length(), 0,3000000,0);
// 				it->second->sessionstatus			= 1;
// 			}
// 		}
// 	}
// 	_mutex.ThreadUnlock();
// }

taskSession_node *CSessionManager::GetTaskNode()
{
	_nodemutex.ThreadLock();
	if(++m_nodeindex > MAX_TASK_NODE - 1)
	{
		m_nodeindex									= 0;//��ȡѭ������Ƶ��ʹ����ͬ����ڵ㣬������̶߳�ͬһ������ڵ��ͬʱ����
	}

	for(;m_nodeindex < MAX_TASK_NODE;m_nodeindex++)
	{
		if(!_sessionlist[m_nodeindex].isused)
		{
			memset(&_sessionlist[m_nodeindex],0,sizeof(taskSession_node));
			_sessionlist[m_nodeindex].nodeindex	= m_nodeindex;
			_sessionlist[m_nodeindex].isused		= 1;
			_nodemutex.ThreadUnlock();
			return	&_sessionlist[m_nodeindex];
		}
	}
	_nodemutex.ThreadUnlock();
	return NULL;
}

void CSessionManager::FreeTaskNode(int	nodeindex)
{
	_nodemutex.ThreadLock();
	memset(&_sessionlist[nodeindex],0,sizeof(taskSession_node));
	_sessionlist[nodeindex].databuf		= NULL;
	_sessionlist[nodeindex].dev			= NULL;
	_sessionlist[nodeindex].headbuf		= NULL;
	_sessionlist[nodeindex].ptrstreamlyer	= NULL;
	_nodemutex.ThreadUnlock();
}

int CSessionManager::CheckRightFun(std::string username,std::string password,FunRightType_m funtype,void *extra,unsigned int &result)
{

	return 0;
}

CSessionManager *CSessionManager::GetInstance()
{
	if (0 == _instance)
	{
		_instance = new CSessionManager();
	}
	return _instance;
}

CMutexUtils CSessionManager::_mutex;
//CMutexUtils CSessionManager::_mutex1;
//CMutexUtils CSessionManager::_nodemutex;
CSessionManager * CSessionManager::_instance = 0;
